﻿using System.IO;

namespace Batman.Cms.Core.Utils
{
    public static class XmlUtil
    {
        public static byte[] Serialize(object obj)
        {
            using (var stream = new MemoryStream())
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
                serializer.Serialize(stream, obj);
                return stream.ToArray();
            }
        }

        public static T Deserialize<T>(string xmlContent) where T : class
        {
            using (var stream = new StringReader(xmlContent))
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                var result = serializer.Deserialize(stream) as T;
                return result;
            }
        }

        public static T Deserialize<T>(byte[] datas) where T : class
        {
            using (var stream = new MemoryStream(datas))
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                var result = serializer.Deserialize(stream) as T;
                return result;
            }
        }

        public static T Deserialize<T>(Stream stream) where T : class
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            var result = serializer.Deserialize(stream) as T;
            return result;
        }
    }
}
